package com.sname.car.security;

import com.sname.car.common.constants.Constants;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author songx
 * @date 2018/9/22 16:49
 */
public class AESUtil {

    /**
     * Author song  醉美柳舞之众星捧月
     * Date & Time  2018/9/22 16:50
     * Description  对称加密算法
     */

    /** 16位加密公钥 **/
    private static final String key = Constants.KEY_16;
    /** 加密类型 */
    public static final String KEY_ALGORITHM = "AES";
    /** 加密模式 */
    public static final String KEY_ALGORITHM_MODE = "AES/CBC/PKCS5Padding";


    /** AES 加密 */
    public static String encrypt(String data) {
        byte[] bs = null;
        try {
            SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), KEY_ALGORITHM);
            // Cipher 是java提供的类拿到加密模式的实例
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_MODE);
            // 初始化的东西要经过上面的东西来描述一下
            cipher.init(Cipher.ENCRYPT_MODE, spec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
            bs = cipher.doFinal(data.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64Util.encode(bs);
    }

    /** AES 解密   key必须16位 */
    public static String decrypt(String data) throws UnsupportedEncodingException {
        byte[] result = null;
        try {
            SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_MODE);
            cipher.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] originBytes = Base64Util.decode(data);
            result = cipher.doFinal(originBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(result, "UTF-8");
    }
}
